from microbit import *

uart.init(115200)


# 确认输出信号
def resetEffect():
    print('\x1e')


# 定义消息前缀和后缀
s = '?'
e = '~'
timeout = 5  # 超时时间5秒钟
stop = 50  # 超时时间120秒


def uart_msg(type='print', *params):
    result = ''.join(map(str, params))
    sleep(100)
    return s + type + '|' + result + e


def cmPrint(*a):
    print(uart_msg('print', *a))


# 等待返回结果
def uart_wait_ok():
    c = 0
    while True:
        r = uart.read(10)
        if c > timeout * 10:
            return -1
        if r != None:
            return r
        else:
            sleep(100)
            c = c + 1


# 等待返回结束
def uart_wait_end():
    c = 0
    while True:
        r = uart.read(10)
        if c > stop * 10:
            return -1
        if r is not None:
            return r
        else:
            sleep(100)
            c = c + 1


# 非阻塞说话
def async_speak(c):
    print(uart_msg('async_speak', c))
    sleep(100)


# 阻塞式说话
def sync_speak(c):
    print(uart_msg('speak', c))
    uart_wait_ok()


# 字符串连接
def str_join(list):
    r = ''
    for item in list:
        r += str(item)
    return r


"""
    下面需要由wood2自动生成初始时间
    year = 2024
    month = 4
    day = 1

    current_s = 48734
"""


def time_add():
    global current_s
    current_s += 5


run_every(time_add, s=5)


def get_time(t: str):
    global year, month, day, week, current_s

    hour = int(current_s / 3600)
    minute = int(current_s % 3600 / 60)
    second = int(current_s % 3600 % 60)

    if t == 'year':
        return year
    if t == 'month':
        return month
    if t == 'day':
        return day

    if t == 'week':
        return week

    if t == 'hour':
        return hour
    if t == 'minute':
        return minute
    if t == 'second':
        return second
    return 0


# 获取系统时间
def get_date(t: str):
    return get_time(t)


# 异步播放音乐
def play_music(name):
    print(uart_msg('async_music', name))
    sleep(100)


# 同步播放音乐
def play_music_until(name):
    print(uart_msg('music', name))
    sleep(100)
    uart_wait_end()


# 同步停止音乐
def stop_music(name):
    print(uart_msg('stop_music', name))
    sleep(100)


resetEffect()
